const db = require('../config/database');
const logger = require('../utils/logger');
const bcrypt = require('bcryptjs');

class UserManagementController {
  // 获取用户列表（后台管理）
  async getUsers(req, res) {
    try {
      const { page = 1, pageSize = 10, status, is_guest, keyword } = req.query;
      const offset = (page - 1) * pageSize;

      let sql = 'SELECT id, username, nickname, phone, openid, is_guest, status, last_login_at, created_at FROM users WHERE 1=1';
      const params = [];

      if (status !== undefined) {
        sql += ' AND status = ?';
        params.push(status);
      }

      if (is_guest !== undefined) {
        sql += ' AND is_guest = ?';
        params.push(is_guest);
      }

      if (keyword) {
        sql += ' AND (username LIKE ? OR nickname LIKE ? OR phone LIKE ?)';
        const likeKeyword = `%${keyword}%`;
        params.push(likeKeyword, likeKeyword, likeKeyword);
      }

      sql += ' ORDER BY created_at DESC LIMIT ? OFFSET ?';
      params.push(parseInt(pageSize), offset);

      const [users] = await db.query(sql, params);

      // 获取总数
      let countSql = 'SELECT COUNT(*) as total FROM users WHERE 1=1';
      const countParams = [];

      if (status !== undefined) {
        countSql += ' AND status = ?';
        countParams.push(status);
      }

      if (is_guest !== undefined) {
        countSql += ' AND is_guest = ?';
        countParams.push(is_guest);
      }

      if (keyword) {
        countSql += ' AND (username LIKE ? OR nickname LIKE ? OR phone LIKE ?)';
        const likeKeyword = `%${keyword}%`;
        countParams.push(likeKeyword, likeKeyword, likeKeyword);
      }

      const [countResult] = await db.query(countSql, countParams);

      res.json({
        success: true,
        data: {
          list: users,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取用户列表失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取用户详情（后台管理）
  async getUserDetail(req, res) {
    try {
      const { id } = req.params;

      const [users] = await db.query(
        'SELECT id, username, nickname, phone, openid, avatar, is_guest, status, last_login_at, created_at, updated_at FROM users WHERE id = ?',
        [id]
      );

      if (users.length === 0) {
        return res.json({
          success: false,
          message: '用户不存在'
        });
      }

      const user = users[0];

      // 获取用户订单统计
      const [orderStats] = await db.query(
        `SELECT 
          COUNT(*) as total_orders,
          SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) as paid_orders,
          SUM(CASE WHEN status = 1 THEN product_price ELSE 0 END) as total_amount
         FROM orders WHERE user_id = ?`,
        [id]
      );

      user.orderStats = orderStats[0];

      res.json({
        success: true,
        data: user
      });
    } catch (error) {
      logger.error('获取用户详情失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 更新用户状态（后台管理）
  async updateUserStatus(req, res) {
    try {
      const { id } = req.params;
      const { status } = req.body;

      if (status === undefined || ![0, 1].includes(status)) {
        return res.json({
          success: false,
          message: '状态值不正确'
        });
      }

      const [result] = await db.query(
        'UPDATE users SET status = ?, updated_at = NOW() WHERE id = ?',
        [status, id]
      );

      if (result.affectedRows === 0) {
        return res.json({
          success: false,
          message: '用户不存在'
        });
      }

      logger.success('更新用户状态', { id, status });

      res.json({
        success: true,
        message: '更新成功'
      });
    } catch (error) {
      logger.error('更新用户状态失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 重置用户密码（后台管理）
  async resetUserPassword(req, res) {
    try {
      const { id } = req.params;
      const { new_password } = req.body;

      if (!new_password || new_password.length < 6) {
        return res.json({
          success: false,
          message: '密码长度不能少于6位'
        });
      }

      const hashedPassword = await bcrypt.hash(new_password, 10);

      const [result] = await db.query(
        'UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?',
        [hashedPassword, id]
      );

      if (result.affectedRows === 0) {
        return res.json({
          success: false,
          message: '用户不存在'
        });
      }

      logger.success('重置用户密码', { id });

      res.json({
        success: true,
        message: '密码重置成功'
      });
    } catch (error) {
      logger.error('重置用户密码失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取用户订单列表（后台管理）
  async getUserOrders(req, res) {
    try {
      const { id } = req.params;
      const { page = 1, pageSize = 10 } = req.query;
      const offset = (page - 1) * pageSize;

      const [orders] = await db.query(
        'SELECT * FROM orders WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?',
        [id, parseInt(pageSize), offset]
      );

      const [countResult] = await db.query(
        'SELECT COUNT(*) as total FROM orders WHERE user_id = ?',
        [id]
      );

      res.json({
        success: true,
        data: {
          list: orders,
          total: countResult[0].total,
          page: parseInt(page),
          pageSize: parseInt(pageSize)
        }
      });
    } catch (error) {
      logger.error('获取用户订单失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 获取用户统计数据（后台管理）
  async getUserStats(req, res) {
    try {
      // 总用户数
      const [totalUsers] = await db.query(
        'SELECT COUNT(*) as total FROM users'
      );

      // 正式用户数
      const [regularUsers] = await db.query(
        'SELECT COUNT(*) as total FROM users WHERE is_guest = 0'
      );

      // 游客用户数
      const [guestUsers] = await db.query(
        'SELECT COUNT(*) as total FROM users WHERE is_guest = 1'
      );

      // 今日新增用户
      const [todayUsers] = await db.query(
        'SELECT COUNT(*) as total FROM users WHERE DATE(created_at) = CURDATE()'
      );

      // 最近7天新增用户
      const [weekTrend] = await db.query(
        `SELECT DATE(created_at) as date, COUNT(*) as count 
         FROM users 
         WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
         GROUP BY DATE(created_at)
         ORDER BY date ASC`
      );

      res.json({
        success: true,
        data: {
          totalUsers: totalUsers[0].total,
          regularUsers: regularUsers[0].total,
          guestUsers: guestUsers[0].total,
          todayUsers: todayUsers[0].total,
          weekTrend
        }
      });
    } catch (error) {
      logger.error('获取用户统计失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }

  // 删除用户（后台管理）
  async deleteUser(req, res) {
    try {
      const { id } = req.params;

      // 检查用户是否有订单
      const [orders] = await db.query(
        'SELECT COUNT(*) as count FROM orders WHERE user_id = ?',
        [id]
      );

      if (orders[0].count > 0) {
        return res.json({
          success: false,
          message: '该用户存在订单记录，无法删除'
        });
      }

      const [result] = await db.query(
        'DELETE FROM users WHERE id = ?',
        [id]
      );

      if (result.affectedRows === 0) {
        return res.json({
          success: false,
          message: '用户不存在'
        });
      }

      logger.success('删除用户', { id });

      res.json({
        success: true,
        message: '删除成功'
      });
    } catch (error) {
      logger.error('删除用户失败', { error: error.message });
      res.json({ success: false, message: '系统错误' });
    }
  }
}

module.exports = new UserManagementController();

